<template>
  <div ref="barChart" class="factory-bar-chart"></div>
</template>
<script lang="ts">
export default {
  name: 'FactoryBarChart'
};
</script>
<script lang="ts" setup>
import { ref, watch, computed, defineProps, onMounted } from 'vue';
import { useECharts } from '@/hooks/useECharts';
import { store } from '@/store';
import { getValueOverflow } from '@/utils';

const barChart = ref();

interface FactoryBarChartProps {
  factoryBarData: any[];
}
const props = defineProps<FactoryBarChartProps>();

const { setOptions } = useECharts(barChart);
const isShowChartLine = computed(() => {
  return store.state.app.globalConfig.isShowChartLine;
});
// 年碳排放趋势 Echart
const renderBarEchart = () => {
  let option: any = {
    color: [
      '#35BD9B'
      // '#2B9496',
      // '#7CA6AC',
      // '#E7EDED',
      // '#B4D9E9',
      // '#6FB1CB',
      // '#CDCDE6',
      // '#8888BD',
      // '#C1D0A7',
      // '#E4D9AB'
    ],
    grid: {
      top: 25,
      left: 20,
      right: 20,
      bottom: 45,
      containLabel: true
    },
    tooltip: {
      appendToBody: true,
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: [
      {
        axisTick: { show: false },
        axisLine: { show: false },
        type: 'category',
        data: props.factoryBarData.map(item => item.name),
        axisLabel: {
          formatter: (value: string) => {
            return getValueOverflow(value, { wordsInALine: 5, lineNum: 2 });
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        splitNumber: 5, // 设置分几段显示
        // label: {
        //   show: false
        // },
        splitLine: {
          show: isShowChartLine.value ?? true
        },
        axisLabel: {
          // 隐藏标签
          show: false
        }
      }
    ],
    dataZoom:
      props.factoryBarData?.length > 6
        ? [
            {
              show: true,
              startValue: 0,
              endValue: 5
            }
          ]
        : undefined,
    series: {
      name: '碳排放量',
      type: 'bar',
      stack: 'Ad',
      barWidth: 28,
      emphasis: {
        focus: 'none'
      },
      label: {
        show: false
      },
      itemStyle: {
        borderRadius: 2,
        width: 28
      },
      data: props.factoryBarData
    }
  };
  return option;
};
function renderChart() {
  const option = renderBarEchart();
  setOptions(option);
}

onMounted(() => {
  renderChart();
});
watch(
  () => props.factoryBarData,
  val => {
    if (val && barChart.value) {
      renderChart();
    }
  }
);
</script>
<style lang="scss" scoped>
.factory-bar-chart {
  width: 100%;
  height: calc(100% - 70px);
}
</style>
